<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

/**
 * 首页接口
 */
class Index extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     * 
     */
    public function index()
    {
        // banner 图
        $banner = Db::name('banner')->select();
        // 秒杀产品
        $spike = Db::name('spike')->limit(4)->select();
        // 积分商品
        $integral = Db::name('integral')->where('integral','>',0)->whereTime('endtime','>',date('Y-m-d H:i:s',time()))->select();
        $starttime = Db::name('spike')->where('endtime','>',time())->where('starttime','>',time())->min('starttime');
        return json_encode(array('banner'=>$banner,'spike'=>$spike,'integral'=>$integral,'time'=>$starttime-time()));
    }
    // 获取换取 openId, sessionKey, unionId
    public function openid(){
        $arrContextOptions=array(
            "ssl"=>array(
                "verify_peer"=>false,
                "verify_peer_name"=>false,
            ),
        );
        $code = $this->request->get('code');
        $appId = 'wx4e96723bd56676c3';
        $Secret = '6b78f796bd45d534909c1bcc9d443875';
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$appId."&secret=".$Secret."&js_code=".$code."&grant_type=authorization_code";
        $weixin = file_get_contents($url, false, stream_context_create($arrContextOptions));
        $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
        $array = get_object_vars($jsondecode);//转换成数组
        return json_encode($array);
    }
    // 添加修改用户信息
    public function user(){
        $openid = $this->request->get('openid');
        $img = $this->request->get('img');
        $name = $this->request->get("name");
        $res = model('People')->add_update_user($openid,$img,$name);
        return $res?json_encode(200):json_encode(400);
    }

}
